####################################
# Timing
####################################

rm(list=ls())

#sink("~/Dropbox/Crime Chile/11_replication/07_timing_crime.txt")

library(Hmisc)
library(ggplot2)
library(stargazer)
library(foreign)
library(rdrobust)
library(rdd)
library(readstata13)

# load function that does clustered SEs
vcovCluster <- function(
  model,
  cluster
)
{
  require(sandwich)
  require(lmtest)
  if(nrow(model.matrix(model))!=length(cluster)){
    stop("check your data: cluster variable has different N than model")
  }
  M <- length(unique(cluster))
  N <- length(cluster)           
  K <- model$rank   
  if(M<40){
    warning("Fewer than 40 clusters, variances may be unreliable")
  }
  dfc <- (M/(M - 1)) * ((N - 1)/(N - K))
  uj  <- apply(estfun(model), 2, function(x) tapply(x, cluster, sum));
  rcse.cov <- dfc * sandwich(model, meat = crossprod(uj)/N)
  return(rcse.cov)
}

################
# Prepare data 
################

# reada data
d = read.dta13("~/Dropbox/Crime Chile/11_replication/local_crime_data_chile_2022january.dta")   
names(d)

############################
# Results
############################

# bandwidth
h0 = rdbwselect(d$propstreetcrime_s,d$margin,cluster = d$cluster)$bws[1]

# timing
d2 = d[!is.na(d$propstreetcrime_s),]
X = d2$margin
center = 0
bw = h0
d2$kweights = kernelwts(X, center, bw, kernel = "triangular")
nrow(d2) - sum(d2$kweights==0)

# effect of alignment
sum(d2$kweights!=0)
h0
reg1 = lm(d2$propstreetcrime_s ~ d2$ruling + d2$margin + as.factor(d2$timing) + d2$ruling*as.factor(d2$timing), weights = d2$kweights)
reg1_c <- round(coeftest(reg1, vcov = vcovCluster(reg1, cluster = d2$cluster)),4)
reg1_c

stargazer(reg1_c, 
          summary=FALSE, 
          rownames=FALSE, 
          keep = c("ruling"),
          covariate.labels = 
          c("Alignment", "Alignment*Second year", "Alignment*Third year", "Alignment*Fourth year"),
          add.lines = list(c("MSE bandwidth","0.096"),c("N","695")),
          out="~/Dropbox/Crime Chile/11_replication/tableA14.html")

sink()
